package us.lithub.ui.activity;

import us.lithub.R;
import us.lithub.Util;
import us.lithub.data.GlobalDb;
import us.lithub.ui.NowPlayingInfo;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.markupartist.android.widget.ActionBar;
/**
 * The Class MainMenu is the first activity displayed to the user, it is the main menu
 */
public class MainMenu extends Activity {

	private static final String TAG = MainMenu.class.getSimpleName();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_menu);        		
		checkVersion();
		new FetchNowPlayingInfoTask().execute();
	}

	/**
	 * Open my library.
	 */
	public void openMyLibrary(View v) {
		startActivity(new Intent(MainMenu.this, MyLibrary.class));
	}

	/**
	 * Open scan book.
	 */
	public void openScanBook(View v) {
		startActivity(new Intent(MainMenu.this, ScanBook.class));
	}

	/**
	 * Open friends.
	 */
	public void openFriends(View v) {
		startActivity(new Intent(MainMenu.this, Friends.class));
	}

	/**
	 * Open lending.
	 */
	public void openLending(View v) {
		startActivity(new Intent(MainMenu.this, Lending.class));
	}

	/**
	 * Open settings.
	 */
	public void openSettings(View v) {
		startActivity(new Intent(MainMenu.this, Settings.class));
	}

	private void checkVersion() {
		try {
			final PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
			final SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
			final int lastRunVersionCode = prefs.getInt("lastRunVersionCode", 0);

			if (lastRunVersionCode == 0) {
				Log.d(TAG, "New install");
				newInstall();

			} else if (lastRunVersionCode < pInfo.versionCode) {
				Log.d(TAG, "New update");
				newUpdate();
			} else {
				Log.d(TAG, "Current");
				current();
				return;
			}

			final Editor editor = prefs.edit();
			editor.putInt("lastRunVersionCode", pInfo.versionCode);
			editor.commit();
		} catch (NameNotFoundException e) {
			Log.e(TAG, "Error checking version: " + e.getMessage());
		}
	}

	private void newInstall() {
		final Dialog homeSetup = new Dialog(MainMenu.this);	
		homeSetup.setContentView(R.layout.dialog_home_setup);
		homeSetup.setTitle("Initial Setup");
		homeSetup.show();

		// handler for the background updating
		final Handler muniHandler = new Handler() {
			TextView status = (TextView) homeSetup.findViewById(R.id.status);
			ProgressBar progress = (ProgressBar) homeSetup.findViewById(R.id.progressBar);
			int mStatus;
			public void handleMessage(Message msg) {
				if (mStatus == Util.PENDING) {
					mStatus = Util.IN_PROGRESS;
					status.setTypeface(null, Typeface.BOLD);
					status.setText("In Progress");
					progress.setProgress(0);
					progress.setMax(msg.arg1);
				} else {
					progress.setProgress(msg.arg2);
					if (msg.arg1 == msg.arg2) {
						mStatus = Util.COMPLETE;
						status.setTypeface(null, Typeface.NORMAL);
						status.setTextColor(Color.GREEN);
						status.setText("Complete");
						homeSetup.dismiss();
					}
				}
			}
		};

		new Thread(new Runnable() {
			public void run() {
				new GlobalDb(MainMenu.this).downloadDatabase(muniHandler);
			}
		}).start();;
	}

	private void newUpdate() {

	}

	private void current() {
		
	}

	/**
	 * Asynchronously fetch whatever data we want to show in the bottom of the screen.
	 * Currently, we are displaying the last commit to our GitHub repository
	 */
	private class FetchNowPlayingInfoTask extends AsyncTask<Void, Void, String> {

		private ActionBar actionbar;
		private WebView webview;

		@Override
		protected void onPreExecute () {
			actionbar = (ActionBar) findViewById(R.id.actionbar);
			actionbar.setProgressBarVisibility(View.VISIBLE);

			webview = (WebView) findViewById(R.id.webview);
			webview.setBackgroundColor(0x00000000);
			webview.loadData("<font color=\"white\"<center>Loading...</center>", "text/html", "UTF-8");
		}
		
		@Override
		protected String doInBackground(Void... arg0) {
			NowPlayingInfo info = new NowPlayingInfo();
			return info.getHtml();
		}

		@Override
		protected void onPostExecute(String html) {
			webview.loadData(html, "text/html", "UTF-8");
			actionbar.setProgressBarVisibility(View.GONE);
		}
	}
}